package cn.wizzer.app.web.modules.controllers.open.file;

import cn.wizzer.app.bus.modules.services.BusinessFileInfoService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Optional;

@IocBean
@At("/open/file/view")
public class ViewFileController {

    private static final Log log = Logs.get();

    @Inject
    private BusinessFileInfoService businessFileInfoService;

    /**
     * 查看图片，通过流的形式输出
     *
     * @param param    有可能传入bus_file_info表中id，通过id查出文件的地址
     *                 也有可能直接传相对地址
     * @param response
     */
    @At("/image")
    @Ok("void")
    @RequiresAuthentication
    public void viewImage(@Param("param") String param, HttpServletResponse response) {
        try {
            String uploadPath = UploadController.getUploadPathConfig();
            String filePath = Optional.ofNullable(this.businessFileInfoService.fetch(param))
                    .map(fileInfo -> uploadPath + fileInfo.getFilePath())
                    .orElseGet(() -> uploadPath + param);
            File file = new File(filePath);
            if (file.exists()) {
                BufferedImage img = ImageIO.read(file);
                if (img != null) {
                    response.setHeader("Content-Type", "image/jpeg");
                    try {
                        ImageIO.write(img, "png", response.getOutputStream());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
